package mongo

import (
	"context"
	"core/datetime"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
)

/*
mongo分页，只能id 倒序
https://blog.csdn.net/m0_56137272/article/details/132629538
*/
type ListDtService[T any] struct {
	ColBaseName string
	Filer       bson.M
	Dtb         time.Time
	Dte         time.Time
}

func (p *ListDtService[T]) Query() (*[]T, error) {

	var r = make([]T, 0)

	for dt := p.Dte.AddDate(0, 0, -1); dt.Unix() >= p.Dtb.Unix(); dt = dt.AddDate(0, 0, -1) {
		var shortdt = datetime.FormatDate(dt)
		var arr, err = p.list(shortdt)

		if err != nil {
			return nil, err
		}
		r = append(r, arr...)
	}

	return &r, nil
}

func (p *ListDtService[T]) list(shortdt string) ([]T, error) {
	var r = make([]T, 0)
	var colname = p.ColBaseName + shortdt
	var col = Db.Collection(colname)

	opts := options.Find().SetSort(bson.D{{"_id", -1}})

	var cur, err = col.Find(context.Background(), p.Filer, opts)
	if err != nil {
		log.Fatal(err)
	}
	defer cur.Close(context.Background())
	for cur.Next(context.Background()) {
		var m T
		err := cur.Decode(&m)
		if err != nil {
			log.Fatal(err)
		}
		r = append(r, m)
	}

	return r, nil
}
